"use strict"
const { users, questionnaire, QSSelect, questionnaireAnswers, userSelect } = require('../models')
const auth = require('../utils/auth');
const dateTime = require('../dateTime');

// 管理员专用视图
var fn_admin = async (ctx, next) => {
    // 用户名
    var username = ctx.session.userName;

    // 管理员首页最新问卷信息
    var NewQS = JSON.parse(JSON.stringify(await questionnaire.findAll({
        order: [
            ['createdAt', 'desc']
        ],
    })));
    // console.log(NewQS);

    // 所有用户
    var allUser = JSON.parse(JSON.stringify(await users.findAll()));

    NewQS.forEach(QS => {
        // console.log(QS);
        // 问卷创建时间
        QS.createTime = dateTime(QS.createdAt)

        // 发布人
        QS.publishUserName = allUser.filter(row => {
            return QS.publishUserId === row.id;
        })[0].userName;
        // console.log(QS.publishUserName);
    })


    var obj = {
        NewQS,
        username
    }
    ctx.render('admin.html', obj);
}

// 管理员查看所有用户界面
var fn_adminAllUser = async (ctx, next) => {
    // 用户名
    var username = ctx.session.userName;

    // 查找所有用户
    var allUser = JSON.parse(JSON.stringify(await users.findAll({
        order: [
            ['id', 'ASC']
        ],
    })));

    allUser.forEach(user => {
        // console.log(user);
        // console.log(user.jurisdiction);

        // 用户权限判断
        if (user.jurisdiction === "1") {
            // console.log(user.jurisdiction);
            user.jurisdictions = '普通用户'
        } else if (user.jurisdiction === "2") {
            // console.log(user.jurisdiction);
            user.jurisdictions = '管理员'
        }
        // console.log(user.jurisdictions);

        //用户状态判断
        if (user.state === "1") {
            // console.log(user.jurisdiction);
            user.states = '正常'
        } else if (user.state === "2") {
            // console.log(user.state);
            user.states = '冻结'
        }
        // console.log(user.states);

        // 用户创建时间
        user.createTime = dateTime(user.createdAt)
    });

    var obj = {
        allUser,
        username
    }
    ctx.render('adminAllUser.html', obj);
}

// 点击用户操作后触发
var fn_userOP = async (ctx, next) => {
    // 点击的管理员
    var adminId = ctx.session.userId;

    // 点击用户操作后获取用户Id
    var userId = ctx.request.body.userId.trim();
    // console.log(userId);

    await userSelect.create({
        userId: userId,
        adminId: adminId
    });

    let res = "";
    res = { code: 200 };
    ctx.body = JSON.stringify(res);

}

// 管理员修改用户信息页面
var fn_userSelect = async (ctx, next) => {
    // 点击的管理员
    var adminId = ctx.session.userId;

    // 查询用户名
    var userClick = JSON.parse(JSON.stringify(await userSelect.findAll({
        order: [
            ['id', 'desc']
        ],
        where: {
            adminId: adminId
        }
    })));
    //   console.log(userClick);

    var currentUserClick = userClick[0].userId;
    // console.log(currentUserClick);

    var currentUser = JSON.parse(JSON.stringify(await users.findOne({
        where: {
            id: currentUserClick
        }
    })));
    //   console.log(currentUser); 

    var currentUserJurisdiction = currentUser.jurisdiction;
    if (currentUserJurisdiction === '1') {
        currentUserJurisdiction = '普通用户'
    } else if (currentUserJurisdiction === '2') {
        currentUserJurisdiction = '管理员'
    }
    // console.log(currentUserJurisdiction);


    var currentUserState = currentUser.state;
    if (currentUserState === '1') {
        currentUserState = '正常'
    } else if (currentUserState === '2') {
        currentUserState = '冻结'
    }
    // console.log(currentUserState);

    // 用户创建时间
    var createTime = dateTime(currentUser.createdAt)


    // 管理员用户名
    var username = ctx.session.userName;

    var obj = {
        username,
        currentUser,
        createTime,
        currentUserJurisdiction,
        currentUserState,
    }
    ctx.render('userSelect.html', obj);
}

// 管理员给用户更新信息
var fn_userUpdate = async (ctx, next) => {

    var userpwd = ctx.request.body.userpwd.trim();
    var userstate = ctx.request.body.userstate.trim();
    var userId = ctx.request.body.userId.trim();
    // console.log(userpwd);
    // console.log(userstate);
    // console.log(userId);

    //更新该用户数据
    await users.update({
        password: userpwd,
        state: userstate,
    }, {
        where: {
            id: userId
        }
    });

    let res = "";
    res = { code: 200 };
    ctx.body = JSON.stringify(res);
}


// 管理员查看调查问卷页面
var fn_adminSelectQS = async (ctx, next) => {
    // 管理员用户名
    var username = ctx.session.userName;

    // 查询所有问卷
    var allQS = JSON.parse(JSON.stringify(await questionnaire.findAll({
        order: [
            ['id', 'ASC']
        ],
    })));

    // 用户表的所有数据
    var userAll = JSON.parse(JSON.stringify(await users.findAll()));

    // 用户回答答案卷的所有数据
    var userSQAll = JSON.parse(JSON.stringify(await questionnaireAnswers.findAll()));

    allQS.forEach(QS => {
        // console.log(QS);
        // console.log(QS.publishUserId);

        // 该问卷发表的用户
        QS.publishUserName = userAll.filter(row => {
            return QS.publishUserId === row.id;
        })[0].userName;
        // console.log(QS.publishUserName);

        //问卷状态判断
        if (QS.state === "1") {
            // console.log(QS.state);
            QS.states = '已发布'
        } else if (QS.state === "2") {
            // console.log(QS.state);
            QS.states = '已下架'
        }
        // console.log(QS.states);

        // 该问卷发表的用户
        QS.userSQAll = userSQAll.filter(row => {
            return QS.id === row.questionnaireId;
        }).length;
        // console.log(QS.userSQAll);

        // 问卷创建时间
        QS.screateTime = dateTime(QS.createdAt)
    })


    var obj = {
        allQS,
        username,
    }
    ctx.render('adminAllQS.html', obj);
}

// 点击查看问卷后触发
var fn_QSOP = async (ctx, next) => {
    // 点击的管理员
    var adminId = ctx.session.userId;

    // 点击用户操作后获取问卷Id
    var QSId = ctx.request.body.QSId.trim();
    // console.log(QSId);

    await QSSelect.create({
        userId: adminId,
        questionnaireId: QSId
    });

    let res = "";
    res = { code: 200 };
    ctx.body = JSON.stringify(res);

}

// 操作问卷页面
var fn_QSSelect = async (ctx, next) => {

    // 点击的管理员
    var adminId = ctx.session.userId;

    // 点击问卷的id
    var userClick = JSON.parse(JSON.stringify(await QSSelect.findAll({
        order: [
            ['id', 'desc']
        ],
        where: {
            userId: adminId
        }
    })))[0].questionnaireId;
    //   console.log(userClick);

    // 查询所有问卷里面问卷id和点击问卷的id相等的
    // 查询问卷
    var SelectQS = JSON.parse(JSON.stringify(await questionnaire.findOne({
        where: {
            id: userClick
        }
    })));
    console.log(SelectQS);

    var selectQSId = SelectQS.id;
    //问卷主题
    var selectQSName = SelectQS.qsName;

    // 问卷发起人
    // 用户表的所有数据
    var publishUser = JSON.parse(JSON.stringify(await users.findOne({
        where: {
            id: SelectQS.publishUserId
        }
    }))).userName;
    // console.log(publishUser);

    //问卷状态
    var currentQSState = SelectQS.state;
    if (currentQSState === '1') {
        currentQSState = '正常'
    } else if (currentQSState === '2') {
        currentQSState = '已下架'
    }
    // console.log(currentQSState);


    //问卷参与人数
    // 用户回答答案卷的所有数据
    var userSQAll = JSON.parse(JSON.stringify(await questionnaireAnswers.findAll()));
    // 该问卷发表的用户
    var QSUserSum = userSQAll.filter(row => {
        return SelectQS.id === row.questionnaireId;
    }).length;
    // console.log(QSUserSum);

    // 问卷创建时间
    var createTime = dateTime(SelectQS.createdAt)


    // 管理员用户名
    var username = ctx.session.userName;

    var obj = {
        selectQSId,
        username,
        selectQSName,
        publishUser,
        QSUserSum,
        createTime
    }
    ctx.render('QSSelect.html', obj);
}

var fn_QSUpdate = async (ctx, next) => {
    var QSstate = ctx.request.body.QSstate.trim();
    var QSId = ctx.request.body.QSId.trim();
    // console.log(QSstate);
    // console.log(QSId);

    //更新该问卷数据
    await questionnaire.update({
        state: QSstate,
    }, {
        where: {
            id: QSId
        }
    });

    let res = "";
    res = { code: 200 };
    ctx.body = JSON.stringify(res);
}

module.exports = {
    '/admin': ['get', auth, fn_admin],
    '/adminAllUser': ['get', fn_adminAllUser],
    '/userSelect': ['get', fn_userSelect],
    '/adminSelectQS': ['get', fn_adminSelectQS],
    '/userOP': ['post', fn_userOP],
    '/userUpdate': ['post', fn_userUpdate],
    '/QSOP': ['post', fn_QSOP],
    '/QSSelect': ['get', fn_QSSelect],
    '/QSUpdate': ['post', fn_QSUpdate],

}